package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //查询分类列表
    @GetMapping("/category/findAll")
    public ResultInfo findAll(){
        List<Category> list = null;
        String categoryKey = "category_list";

        if (redisTemplate.hasKey(categoryKey)) {
            list  = (List<Category>) redisTemplate.opsForValue().get(categoryKey);

        }else {
            list = categoryService.findAll();
            redisTemplate.opsForValue().set(categoryKey,list);
        }

        return ResultInfo.success(list);
    }

    //增加分类
    @PostMapping("/category")
    public ResultInfo add(@RequestBody Category category){
        categoryService.add(category);
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }

    //修改分类
    @PutMapping("/category")
    public ResultInfo update(@RequestBody Category category){
        categoryService.update(category);
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }

    //删除分类
    @DeleteMapping("/category")
    public ResultInfo delete(Long id){
        categoryService.delete(id);
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }

    //根据type查询
    @GetMapping("/category/list")
    public ResultInfo list(Integer type){
        return ResultInfo.success(categoryService.list(type));
    }


}
